<!--
 @description 经销商档案新建 编辑
 @fileName Edit.vue
 @author zengqiongying
 @created 2023-04-30 17:18:14
-->
<template>
  <div class="has-foot-pb">
    <Card>
      <DealerCell :detail="dealerData" />
    </Card>
    <Card v-for="(item, i) in progressInfoItems" :key="i" v-show="item.show">
      <div class="editItem" @click.stop="toEditPage(item.code)">
        <qmp-circle
          :current-rate="item.rate"
          :rate="100"
          :speed="100"
          :text="`${item.rate}%`"
          :stroke-width="80"
          :size="58"
          :layer-color="item.rate === 0 ? '#FFF3DB' : '#E9ECEC'"
          :color="item.rate === 0 ? '#FFF3DB' : '#149774'"
        >
          <div class="text" :class="{ warning: item.rate === 0, normal: item.rate !== 0 }">{{ item.rate || 0 }}%</div>
        </qmp-circle>
        <div>
          <div class="name">{{ item.title }}</div>
          <div class="state">{{ item.info }}</div>
        </div>
        <qmp-icon class="icon" name="arrow" />
      </div>
    </Card>

    <div class="ctm-content-foot">
      <div class="btn radius-larg ctm-btn-warning" @click="onSave">提交</div>
      <div class="btn radius-larg ctm-btn-main" @click="onView">预览</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick, computed } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import DealerCell from '@/components/DealerCell/index.vue'
  import { detail, getProgress, submitChange } from '@/apis/dealerMarketing/NewArchive'
  import { createSave } from '@/apis/ctmCustomerChange'

  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerNewArchiveEdit',
    components: { Card, DealerCell },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const $route = useRoute()
      const datas = reactive<anyObjectModle>({
        id: $route.query.id || '',
        detail: {},
        progressInfoItems: [
          {
            code: 'basicInfo',
            title: '经销商基本信息',
            info: '完成填写基本信息',
            rate: 0
          },
          {
            code: 'address',
            title: '经销商收货地址信息',
            info: '收货地址可以填写多个',
            rate: 0,
            show: false
          },
          {
            code: 'contacts',
            title: '经销商联系人信息',
            info: '填写相关联系人',
            rate: 0,
            show: false
          },
          {
            code: 'partner',
            title: '经销商合伙经营信息',
            info: '有合伙人才填写',
            rate: 0,
            show: false
          },
          {
            code: 'handover',
            title: '经销商交接情况',
            info: '如果是交接才需要填写',
            rate: 0,
            show: false
          },
          {
            code: 'shop',
            title: '门店信息',
            info: '只填写一个门店信息',
            rate: 0,
            show: false
          },
          {
            code: 'shopContacts',
            title: '门店联系人',
            info: '填写门店联系人信息',
            rate: 0,
            show: false
          },
          {
            code: 'reportPic',
            title: '门店报图情况',
            info: '填写门店装修报图',
            rate: 0,
            show: false //经销商交接（isMarketConnect=1）且是否接管原商家门店为是 （isTakeOverTheOriginalStore =1 ）时，不显示“门店报图情况”
          }
        ]
      })
      const dealerData = computed(() => {
        const d = { ...datas.detail }
        return {
          code: d.customerCode || '',
          name: d.customerName || '',
          officeCode: d.officeCode || '',
          officeName: d.officeName || '',
          createBy: d.createBy || ''
        }
      })
      const getDetail = async () => {
        const id = `${datas.id}`
        await detail(id).then((res) => {
          datas.detail = res.data || {}
        })
        getProgress(id).then((res) => {
          const progressItems = datas.progressInfoItems
          if (res.data) {
            const d = res.data
            const rateObj: anyObjectModle = {
              basicInfo: d.progressInfo,
              address: d.progressAddress,
              contacts: d.progressInfoContact,
              partner: d.progressPartner,
              shop: d.progressShop,
              shopContacts: d.progressShopContact,
              reportPic: d.progressReportPic,
              handover: d.progressHandover
            }
            const { isTakeOverTheOriginalStore, isMarketConnect } = datas.detail
            datas.progressInfoItems = progressItems.map((v: any) => {
              let rate = rateObj[v.code] || 0
              let show = true
              if (v.code === 'reportPic') {
                // 经销商交接（isMarketConnect=1）且是否接管原商家门店为是 （isTakeOverTheOriginalStore =1 ）时，不显示“门店报图情况”
                show =
                  [1, '1'].includes(isMarketConnect) && [1, '1'].includes(isTakeOverTheOriginalStore) ? false : true
              }
              return {
                ...v,
                ...{ rate, show }
              }
            })
          }
        })
      }

      const onSave = () => {
        const flag = datas.progressInfoItems.every((v: any) => v.rate === 100)
        if (!flag) {
          proxy.$toast('信息填写不完整，不能提交')
          return
        }
        const data = { id: datas.id }
        submitChange(data).then(() => {
          proxy.$toast('提交成功')
          proxy.$SimpleEvents.emit('refreshCustomerChangeItem', data.id)
          nextTick(() => {
            $router.goBack()
          })
        })
      }

      const onView = () => {
        $router.push({
          path: '/dealerNewArchive/preview',
          query: {
            id: `${datas.id}`
          }
        })
      }
      const toEditPage = (path: string) => {
        const { detail } = datas
        if (path === 'partner') {
          if (!detail.isPartnership) {
            proxy.$toast('非合伙经营，不能操作')
            return
          }
        } else if (path === 'handover') {
          /* if (!detail.isMarketConnect) {
            proxy.$toast('非经销商交接，不能操作')
            return
          } */
        } else if (path === 'shopContacts' || path === 'reportPic') {
          if (!(detail.shopDTO && detail.shopDTO.id) && !(detail.shopDTOS && detail.shopDTOS.length > 0)) {
            proxy.$toast('未创建门店信息，不能操作')
            return
          }
        }
        if (path === 'shop' && [1, '1'].includes(detail.isTakeOverTheOriginalStore)) {
          // 接管原商家店铺
          path = 'originalStore'
        }
        $router.push({
          path: `/dealerNewArchive/${path}`,
          query: {
            id: `${datas.id}`,
            changeCode: `${datas.detail.code}`
          }
        })
      }
      proxy.$SimpleEvents.registerEvent('refreshCustomerNewArchiveEditInfo', () => {
        getDetail()
      })

      onBeforeRouteLeave((to, from) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerInfoNewArchive', 'DealerNewArchiveAdd', 'DealerNewArchiveDetail'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
      })

      getDetail()
      return {
        ...toRefs(datas),
        dealerData,
        onSave,
        onView,
        toEditPage
      }
    }
  }
</script>
<style lang="less" scoped>
  .editItem {
    padding: 0 16px;
    position: relative;
    display: flex;
    align-items: center;
    /deep/ .qmp-circle {
      margin-right: 14px;
      .text {
        position: absolute;
        left: 0;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font: var(--font-main-body);
        &.normal {
          color: var(--texticon-color-brand-normal);
        }
        &.warning {
          color: var(--texticon-color-warning-normal);
        }
      }
    }
    .icon {
      position: absolute;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
      color: var(--texticon-default-normal);
    }
    .name {
      font: var(--font-main-title-strengthen);
      color: var(--texticon-default-strong);
    }
    .state {
      margin-top: 2px;
      font: var(--font-main-body);
      color: var(--texticon-default-strong);
    }
  }
</style>
